package TreeSeries;

import java.util.*;

public class PreorderTraversalByIterativeSolution_144 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        if(root !=null) {
            stack.push(root);
        }
        while(!stack.isEmpty()) {
            TreeNode node = stack.peek();
            if(node!=null) {
                stack.pop();
                if(node.right!=null) stack.push(node.right);
                if(node.left!=null) stack.push(node.left);
                stack.push(node);
                stack.push(null);

            }
            // 如果是null，说明是被标记的node
            else {
                stack.pop();
                result.add(stack.pop().val);
            }
        }
        return result;
    }
}